'use strict';
const qiniu = require('qiniu');
const accessKey = 'cOENxQ8MTRoh2pgTRY58UjwUx51PyoMiXQAw9B0k';
const secretKey = 'Of40rBuhrXYV_GHcv-Vp2qXoQ9sag-ShnRhNAIzm';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
// 上传空间
const bucket = 'moyushop';
const options = {
  scope: bucket,
};

const qiniuUrl = 'http://boyashop.boya888.xyz';

const putPolicy = new qiniu.rs.PutPolicy(options);

// 七牛云文件下载
// function downloadFile(key) {
//   const url = 'http://boyashop.mfish.xyz/' + key;
//   const policy = new qiniu.rs.GetPolicy();
//   // 生成下载链接url
//   const downloadUrl = policy.makeRequest(url);
//   console.log('downloadUrl:', downloadUrl);
// }


// 构造上传函数
function qiniuUploadFile(file) {
  // console.log('qiniuUploadFile file:', file);
  // 获取文件扩展名
  const oFilename = file.filename;
  const oFilenameArr = oFilename.split('.');
  const extName = oFilenameArr[oFilenameArr.length - 1];

  const fileName = (+new Date()) + (Math.random() + '').slice(2, 10) + '.' + extName;
  // 生成上传token
  const uptoken = putPolicy.uploadToken(mac);
  const config = new qiniu.conf.Config();
  // 空间对应的机房
  config.zone = qiniu.zone.Zone_z1;
  const formUploader = new qiniu.form_up.FormUploader(config);
  const putExtra = new qiniu.form_up.PutExtra();


  return new Promise((resolve, reject) => {
    formUploader.putFile(uptoken, fileName, file.filepath, putExtra, function(respErr,
      respBody, respInfo) {
      // console.log('respErr:', respErr);
      // console.log('respBody:', respBody);
      // console.log('respInfo:', respInfo);
      if (respErr) {
        reject(respErr);
        throw respErr;
      }
      if (respInfo.statusCode === 200) {
        resolve({ ...respBody, url: qiniuUrl + '/' + respBody.key });
        // console.log(respBody);
      } else {
        reject(respInfo);
        // console.log(respInfo.statusCode);
        // console.log(respBody);
      }
    });
  });
}


module.exports = {
  qiniuUploadFile,
};

